<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/5/28
 * Time: 下午6:33
 */

namespace EasySwoole\EasySwoole;


use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use App\Process\HotReload;
use EasySwoole\Http\Request;
use EasySwoole\Http\Message\Status;
use EasySwoole\Http\Response;
use EasySwoole\Utility\File;
use EasySwoole\Component\Pool\PoolManager;
use App\Utility\Pool\MysqlPool;

class EasySwooleEvent implements Event
{

    public static function initialize()
    {
        define( 'APP_PATH', __DIR__.'/App/' );
        date_default_timezone_set('PRC');
        //引用自定义文件配置
        self::loadConf();
        //注册mysql数据库连接池
        PoolManager::getInstance()->register(MysqlPool::class, Config::getInstance()->getConf('database.pool_max_num'));
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // 自定义进程注册
        $swooleServer = ServerManager::getInstance()->getSwooleServer();
        $swooleServer->addProcess((new HotReload('HotReload', ['disableInotify' => false]))->getProcess());
        //注册onWorkerStart回调事件
//        $register->add($register::onWorkerStart, function (\swoole_server $server, int $workerId) {
//            if ($server->taskworker == false) {
//                //新增preload方法,可在程序启动后预创建连接,避免在启动时突然大量请求,造成连接来不及创建从而失败的问题.
//                //预创建数量,必须小于连接池最大数量
//                PoolManager::getInstance()->getPool(MysqlPool::class)->preLoad(5);
//            }
//        });
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        //跨域
        $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->withHeader('Access-Control-Allow-Credentials', 'true');
        $response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        if ($request->getMethod() === 'OPTIONS') {
            $response->withStatus(Status::CODE_OK);
            $response->end();
        }
        $response->withHeader('Access-Control-Allow-Origin', '*');
    }

    public static function onReceive(\swoole_server $server, int $fd, int $reactor_id, string $data):void
    {

    }

    /**
     * 引用自定义配置文件
     * @throws \Exception
     */
    public static function loadConf()
    {
        $files = File::scanDirectory(EASYSWOOLE_ROOT . '/App/Config');
        if (is_array($files)) {
            foreach ($files['files'] as $file) {
                $fileNameArr = explode('.', $file);
                $fileSuffix = end($fileNameArr);
                if ($fileSuffix == 'php') {
                    Config::getInstance()->loadFile($file);
                }
            }
        }
    }

}
